package uade.distribuidas.server.dao;


import java.util.List;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;

import uade.distribuidas.repo.exception.ExceptionFactura;
import uade.distribuidas.server.domain.Factura;
import uade.distribuidas.server.hibernate.HibernateUtil;

public class FacturasDAO {

	private static FacturasDAO instancia = null;
	private static SessionFactory sf = null;

	public static FacturasDAO getInstancia(){
		if(instancia == null){
			sf = HibernateUtil.getSessionFactory();
			instancia = new FacturasDAO();
		} 
		return instancia;
	}
	
	@SuppressWarnings("unchecked")
	public List<Factura> getFacturas()throws ExceptionFactura{
		Session session = sf.openSession();
		
		List<Factura> lista = session.createQuery("from Factura").list();		
	
		
		session.close();
		return lista;
	}
	
	
	public Factura getFactura(Integer id)throws ExceptionFactura{
		Session session = sf.openSession();
		
		Factura f = (Factura) session.createQuery("from Factura where id = :id")
				.setParameter("id", id)
				.uniqueResult();			
		
		session.close();
		return f;
	}

	public Factura save(Factura f) throws ExceptionFactura{
		Session session = sf.openSession();
		 Transaction transaction = session.beginTransaction();
		 transaction.begin();
		 session.saveOrUpdate(f);
		 transaction.commit();
		 session.close();
		 return f;
	}
	
	

}
